package org.docmanagement.services.impl;

import java.util.List;

import org.docmanagement.commons.service.GenericServiceImpl;
import org.docmanagement.data.TodoItem;
import org.docmanagement.services.TodoException;
import org.docmanagement.services.TodoService;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("todoService")
@Transactional
public class TodoServiceImpl extends GenericServiceImpl<TodoItem> implements TodoService {

	@Autowired
    public TodoServiceImpl(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

	protected Class<TodoItem> getObjectClass() {
		return TodoItem.class;
	}

	@SuppressWarnings("unchecked")
	public List<TodoItem> findByCategory(String name) throws TodoException {
		try {
			DetachedCriteria criteria = DetachedCriteria.forClass(getObjectClass());
			criteria.add(Restrictions.like("category", name));
			return criteria.getExecutableCriteria(getSession()).list();
		} catch (HibernateException e) {
			throw new TodoException("Can't retreive todo items for category " + name, e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<TodoItem> findWithNoCategory() throws TodoException {
		try {
			DetachedCriteria criteria = DetachedCriteria.forClass(getObjectClass());
			criteria.add(Restrictions.isNull("category"));
			return criteria.getExecutableCriteria(getSession()).list();
		} catch (HibernateException e) {
			throw new TodoException("Can't retreive todo items", e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<String> getCategoryList() throws TodoException {
		try {
			return getHibernateTemplate().find(
					"select distinct todo.category from TodoItem todo where todo.category != ''");
		} catch (HibernateException e) {
			throw new TodoException("Can't retreive category list", e);
		}
	}
}
